// lib/network/dio_service.dart
import 'package:dio/dio.dart';
import 'package:labcloud_app/datas/base_model.dart';

class DioService {
  static final DioService _instance = DioService._internal();
  late Dio _dio;

  factory DioService() {
    return _instance;
  }

  DioService._internal() {
    _dio = Dio();

    // 配置默认选项
    _dio.options = BaseOptions(
      baseUrl: 'http://192.168.31.131:8081', // 替换为你的API基础URL
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
      headers: {'Content-Type': 'application/json; charset=UTF-8'},
    );

    // 添加拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(

        onRequest: (options, handler) {
          // 请求前处理
          print('请求: ${options.method} ${options.path}');
          print('请求参数: ${options.data}');
          return handler.next(options);
        },

        onResponse: (response, handler) {
          // 响应处理
          print('响应数据: ${response.data}');
          var bm = BaseModel.fromJson(response.data);
          // 检查业务逻辑错误
          // 如果code不为0，表示业务逻辑错误
          if (bm.code != null && bm.code != 0) {
            final message = bm.message ?? '未知错误';
            return handler.reject(
              DioException(
                error: message,
                requestOptions: response.requestOptions,
                response: response,
                type: DioExceptionType.badResponse,
              ),
            );
          }

          // 创建新的响应对象，只包含data部分
          final newResponse = Response(
            data: bm.data,
            headers: response.headers,
            requestOptions: response.requestOptions,
            statusCode: response.statusCode,
            statusMessage: response.statusMessage,
          );
          // 如果data为null但code为0，也视为成功
          // 正常返回响应
          return handler.next(newResponse);
        },

        onError: (DioException e, handler) {
          // 错误处理
          print('请求错误: ${e}');
          
          // 打印详细的错误信息
          if (e.response != null) {
            print('错误状态码: ${e.response!.statusCode}');
            print('错误响应数据: ${e.response!.data}');
            
            // 尝试解析错误响应中的业务错误信息
            try {
              if (e.response!.data is Map) {
                var errorData = e.response!.data as Map;
                var code = errorData['code'] ?? '未知';
                var message = errorData['message'] ?? '未知错误';
                print('业务错误码: $code');
                print('业务错误信息: $message');
              }
            } catch (parseError) {
              print('解析错误响应失败: $parseError');
            }
          } else {
            print('请求错误信息: ${e.message}');
          }
          
          return handler.next(e);
        },

      ),
    );
  }

  // GET 请求
  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.get<T>(
      path,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
    );
  }

  // POST 请求
  Future<Response<T>> post<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.post<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
    );
  }

  // PUT 请求
  Future<Response<T>> put<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.put<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
    );
  }

  // DELETE 请求
  Future<Response<T>> delete<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.delete<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
    );
  }
}
